package com.sense.kukoo.common.wiget.dialog

/*
class MediaListDialog(context: Context) : Dialog(context) {

    private val TAG: String = javaClass.simpleName
    private lateinit var root: View
    private lateinit var multiState: MultiStateContainer
    private lateinit var play_list: View
    private lateinit var play_list_content: View
    private lateinit var content_list: View
    private lateinit var blur: View
    private lateinit var tv_btn_clean_all: View
    private lateinit var iv_blur: ImageView
    private lateinit var refreshLayout_1: SmartRefreshLayout
    private lateinit var refreshLayout_2: SmartRefreshLayout
    private lateinit var recyclerView_1: RecyclerView
    private lateinit var recyclerView_2: RecyclerView
    private lateinit var tv_episodes: TextView
    private lateinit var tv_title_first: TextView

    private lateinit var mMediaAdapter: com.sense.kukoo.biz_media.adapter.MediaAdapter
    private lateinit var mMediaListAdapter: com.sense.kukoo.biz_media.adapter.MediaListAdapter

    private val defTranslationY: Float = ApplicationContext.dp2px(8f).toFloat()
    private val toDismissPercent: Float = 0.3F
    private val mAnimHeight: Float = 800f
    private val mAnimTime: Long = 300

    private var touchY: Float = Float.MIN_VALUE
    private var translationY: Float = defTranslationY
    private var translationX: Float = 0F
    private var rightContentWidth: Float = 0F
    private var state = STATE_SUCCESS
    private var mPlayState: Int = UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING

    private var mIndex = 1
    private val mPageSize = 20
    private val mListItems:ArrayList<BookItemBean> = arrayListOf()
    private var mCurrentMediaListItem:LocalMediaListItemBean? = null

    private var mCurrentMusicState: Int = UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING
    private var mCurrentMusicProgress: Int = 1

    private var mIsTouching = false

    companion object {
        val STATE_SUCCESS = 0
        val STATE_EMPTY = 1
    }

    private val mWatcher = object:UserWatcher.MusicStateWatcher{
        override fun onMusicChanged(music: LocalMediaListItemBean) {
            mMediaListAdapter.setCurrentMusic(music)
            mMediaAdapter.setCurrentMusic(music)
        }

        override fun onPlayTimeChanged(currentInt: Int, totalInt: Int, current: String, total: String) {}

        override fun onPlayPercentChanged(percent: Int) {
            if(!mIsTouching && mCurrentMusicProgress != percent){
                mCurrentMusicProgress = percent
                mMediaAdapter.setCurrentPlayState(mCurrentMusicState, mCurrentMusicProgress)
            }
        }

        override fun onPlayStateChanged(state: Int) {
            mPlayState = state
            if(!mIsTouching && mCurrentMusicState != state){
                mCurrentMusicState = state
                mMediaAdapter.setCurrentPlayState(mCurrentMusicState, mCurrentMusicProgress)
            }
        }

        override fun onPlaySpeedChanged(speed: Float) {}

        override fun onPlayListChanged() {
            //播放列表变化
            refreshPlayListData()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        context.setTheme(R.style.bottom_dialog)
        setContentView(R.layout.common_dialog_media_list)
        //
        root = findViewById<View>(R.id.root)
        multiState = findViewById<MultiStateContainer>(R.id.multi_state)
        play_list = findViewById<View>(R.id.play_list)
        play_list_content = findViewById<View>(R.id.play_list_content)
        content_list = findViewById<View>(R.id.content_list)
        blur = findViewById<View>(R.id.blur)
        tv_btn_clean_all = findViewById<View>(R.id.tv_btn_clean_all)
        iv_blur = findViewById<ImageView>(R.id.iv_blur)
        refreshLayout_1 = findViewById<SmartRefreshLayout>(R.id.refreshLayout_1)
        refreshLayout_2 = findViewById<SmartRefreshLayout>(R.id.refreshLayout_2)
        recyclerView_1 = findViewById<RecyclerView>(R.id.recyclerView_1)
        recyclerView_2 = findViewById<RecyclerView>(R.id.recyclerView_2)
        tv_episodes = findViewById<TextView>(R.id.tv_episodes)
        tv_title_first = findViewById<TextView>(R.id.tv_title_first)

        tv_btn_clean_all.setOnClickListener {
            showCleanAllDialog()
        }
        findViewById<View>(R.id.blur).setOnClickListener {
            dismissContentList()
        }
        //
        initTouchEvent()
        //
        initRefresh1()
        initRefresh2()
    }

    override fun show() {
        super.show()
        root.setTranslationY(ApplicationContext.dp2px(mAnimHeight).toFloat())
        root.animate()
            .translationY(defTranslationY)
            .setDuration(getAnimDuration((mAnimHeight)))
            .withEndAction {
                initViewSizeAndPlace()
                Kukoo.watcher.register(mWatcher)
            }
            .start()
    }

    override fun dismiss() {
        val animDuration = getAnimDuration(root.height - root.translationY)
        root.animate()
            .translationY(ApplicationContext.dp2px(root.height.toFloat()).toFloat())
            .setDuration(animDuration)
            .withEndAction(Runnable {
                Kukoo.watcher.unregister(mWatcher)
                _dismiss()
            })
            .start()
    }

    private fun _dismiss() {
        super.dismiss()
    }

    private fun initViewSizeAndPlace() {
        rightContentWidth = content_list.width.toFloat()
        content_list.translationX = rightContentWidth
        content_list.visibility = View.VISIBLE
    }

    private fun initTouchEvent() {
        root.setOnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
                    onTouchStart(event.y)
                }
                MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
                    onTouchFinish(event.y)
                    v.performClick()
                }
            }
            return@setOnTouchListener true
        }
    }

    private fun onTouchStart(y: Float) {
        if (touchY == Float.MIN_VALUE) {
            touchY = y
        }
        val moveY: Float = y - touchY
        translationY += moveY
        if (translationY > 0) {
            root.translationY = translationY
        }
        LoggerManager.d(
                TAG,
                "onTouchStart -> y=${y}, touchY=${touchY}, moveY=${moveY}, translationY=${translationY}"
        )
    }

    private fun onTouchFinish(y: Float) {
        LoggerManager.d(TAG, "onTouchFinish -> translationY=${translationY}, height=${root.height}")
        val toDismiss: Boolean = translationY > root.height * toDismissPercent
        if (toDismiss) {
            dismiss()
        } else {
            val animDuration = getAnimDuration(translationY - defTranslationY)
            root.animate().translationY(defTranslationY).setDuration(animDuration).start()
        }
        touchY = Float.MIN_VALUE
        translationY = defTranslationY
    }

    private fun getAnimDuration(moveY: Float): Long {
        var duration = (mAnimTime * (moveY / mAnimHeight)).toLong().absoluteValue
        duration = if (duration > mAnimTime) mAnimTime else duration
        return duration
    }

    private var isShowRightContent: Boolean = false

    private fun showContentList(runnable:Runnable ) {
        isShowRightContent = true
        //blur
        blur.visibility = View.VISIBLE
        val blur = BlurKit.getInstance().fastBlur(play_list_content, 10, 0.3F)
        iv_blur.setImageBitmap(blur)
        iv_blur.alpha = 0F
        iv_blur.animate().alpha(1F).setDuration(mAnimTime).start()
        //
        play_list_content.animate().alpha(0.4F).setDuration(mAnimTime).start()
        play_list.animate().translationX(-rightContentWidth).setDuration(mAnimTime).start()
        content_list.animate().translationX(0F).setDuration(mAnimTime).withEndAction(runnable).start()
    }

    private fun dismissContentList() {
        //
        isShowRightContent = false
        //
        val runnable = {
            //清理右侧列表数据
            mCurrentMediaListItem = null
            mListItems.clear()
            showListData()
        }
        //blur
        iv_blur.animate().alpha(0F).setDuration(mAnimTime).withEndAction {
            blur.visibility = View.GONE
            iv_blur.setImageBitmap(null)
        }.start()
        play_list_content.animate().alpha(1F).setDuration(mAnimTime).start()
        play_list.animate().translationX(0F).setDuration(mAnimTime).start()
        content_list.animate().translationX(rightContentWidth).setDuration(mAnimTime).withEndAction(runnable).start()
    }

    private fun showCleanAllDialog() {
        val dialog = MiddleConfigDialog(context)
        val mListener = object : MiddleConfigDialog.MiddleConfigListener {
            override fun onLeftClick() {
                dialog.dismiss()
            }

            override fun onRightClick() {
                dialog.dismiss()
                //todo setState(STATE_EMPTY)
                Kukoo.input.deleteAll()
            }
        }
        dialog
            .setTitleStr(ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.media_controler_clean_title))
            .setMsgStr(ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.media_controler_clean_hint))
            .setBtnLeft(
                    ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.settings_cache_left_btn),
                    context.getResources()
                        .getColor(com.sense.kukoo.common.R.color.dialog_btn_text_color_blue)
            )
            .setBtnRight(
                    ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.settings_cache_right_btn),
                    context.getResources()
                        .getColor(com.sense.kukoo.common.R.color.dialog_btn_text_color_red)
            )
            .setListener(mListener)
            .show()
        LoggerManager.e("text=${ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.media_controler_clean_hint)}")
    }

    private fun setState(s: Int) {
        if (state != s) {
            state = s
            when (state) {
                STATE_SUCCESS -> {
                    multiState.show<SuccessState>()
                    tv_btn_clean_all.visibility = View.VISIBLE
                }
                STATE_EMPTY -> {
                    multiState.show<EmptyState> {
                        it.onExplore {
                            EventBus.getDefault().post(MainPageEvent(0))
                            ARouter.getInstance()
                                .build(ARouterUrl.ROUTE_MAIN_MODULE_MAIN_ACTIVITY)
                                .navigation()
                            dismiss()
                        }
                    }
                    tv_btn_clean_all.visibility = View.GONE
                }
            }
        }
    }

    private fun initRefresh1() {
        //init
        mMediaAdapter = com.sense.kukoo.biz_media.adapter.MediaAdapter(arrayListOf(), mMediaListener)
        recyclerView_1.adapter = mMediaAdapter
        val linearLayoutManager = LinearLayoutManager(context)
        recyclerView_1.layoutManager = linearLayoutManager
        refreshLayout_1.setEnableRefresh(false)
        refreshLayout_1.setEnableLoadMore(false)
        //load data
        refreshPlayListData()
    }

    private fun refreshPlayListData(){
        val data = arrayListOf<MediaItemBean>()
        val list = Kukoo.playlist.getList()
        if(list.size == 0){
            setState(STATE_EMPTY)
        }else{
            setState(STATE_SUCCESS)
            list.forEach {
                data.add(MediaItemBean(data = it))
            }
            mMediaAdapter.list = data
            mMediaAdapter.notifyDataSetChanged()
        }

    }

    val mMediaListener = object : com.sense.kukoo.biz_media.adapter.MediaAdapter.MediaListener {
        override fun onItemClick(bean: MediaItemBean, position: Int) {
            val data: LocalMediaListItemBean = bean.data
            LoggerManager.d("onItemClick data.type=${data.type}, data.isChapter=${data.isChapter}")
            if(data.type == BookBean.TYPE_PODCAST */
/*&& data.isChapter == 1*//*
){
                //播客单集
                ARouter.getInstance()
                    .build(ARouterUrl.ROUTE_MEDIA_MODULE_PODCAST_DETAIL_ACTIVITY)
                    .withInt(ARouterUrl.KEY_FROM, 3)
                    .withParcelable(ARouterUrl.KEY_LOCAL_MEDIA_LIST_ITEMBEAN, data)
                    .navigation()
            }else{
                ARouter.getInstance()
                    .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_LIST_DETAIL_ACTIVITY)
                    .withString(ARouterUrl.KEY_BOOK_ID_STR, ""+bean.data.idOfBooks())
                    .navigation()
            }
        }

        override fun onMediaPlayClick(bean: MediaItemBean, position: Int) {
            val data:LocalMediaListItemBean = bean.data
            val currentPlayMusic = Kukoo.play.getCurrentPlayMusic()
            if(currentPlayMusic?.idOfChapter() == data.idOfChapter()){
                //当前的
                when (mPlayState) {
                    UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
                    UserWatcher.MusicStateWatcher.STATE_SEEKING,
                    UserWatcher.MusicStateWatcher.STATE_PREPARE,
                    UserWatcher.MusicStateWatcher.STATE_PLAYING -> {
                        Kukoo.input.pause()
                    }
                    */
/*
                    UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING ->{}
                    UserWatcher.MusicStateWatcher.STATE_PAUSE ->{}
                    *//*

                    else -> {
                        Kukoo.input.start()
                    }
                }
            }else{
                //非当前的
                Kukoo.input.play(data)
            }
        }

        override fun onMediaToList(bean: MediaItemBean, position: Int) {
            showContentList {
                loadMediaListData(bean)
            }
        }

        override fun onMediaDelete(bean: MediaItemBean, position: Int) {
            Kukoo.input.delete(bean.data)
        }

        override fun onTouchChanged(isTouching: Boolean) {
            mIsTouching = isTouching
            LoggerManager.d(TAG,"onTouchChanged=${isTouching}")
        }
    }

    private fun initRefresh2() {
        //init
        mMediaListAdapter = com.sense.kukoo.biz_media.adapter.MediaListAdapter(arrayListOf(), mMediaListListener)
        recyclerView_2.adapter = mMediaListAdapter
        val linearLayoutManager = LinearLayoutManager(context)
        recyclerView_2.layoutManager = linearLayoutManager
        refreshLayout_2.setOnRefreshListener {
            //OnRefresh
            refreshListData()
        }
        refreshLayout_2.setOnLoadMoreListener {
            //OnLoadMore
            loadMoreListData()
        }
    }

    val mMediaListListener = object : com.sense.kukoo.biz_media.adapter.MediaListAdapter.MediaListListener {

        override fun onItemClick(bean: MediaListItemBean, position: Int) {
            val data:LocalMediaListItemBean = LocalMediaListItemBean(bean.data)
            data.mCoverUrl = mCurrentMediaListItem?.mCoverUrl
            data.name = mCurrentMediaListItem?.name
            data.isSubscription = mCurrentMediaListItem?.isSubscription
            data.chapterTotal = mCurrentMediaListItem?.chapterTotal
            data.isChapter = mCurrentMediaListItem?.isChapter
            data.type = mCurrentMediaListItem?.type ?: 0
            //
            Kukoo.input.play(data)
            //打开播放页
            MediaControlerDialog(getContext()).show()
        }
    }

    fun loadMediaListData(bean: MediaItemBean) {
        val data: LocalMediaListItemBean = bean.data
        mCurrentMediaListItem = data
        //load data
        tv_episodes.setText(ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.media_controler_episodes, data.chapterTotal))
        tv_title_first.text = data.titleOfBooks()
        //
        refreshLayout_2.autoRefresh()
    }

    private fun refreshListData(){
        GlobalScope.launch(Dispatchers.IO){
            val asc = Repo.bookSequence.get(mCurrentMediaListItem!!.idOfBooks())
            val bookQueryPage = MediaModel().bookQueryPage(mCurrentMediaListItem!!.idOfBooks(), 1, mPageSize, asc)
            if (bookQueryPage.success) {
                val items: QueryPageBean<BookItemBean> = bookQueryPage.data!!
                val records = items.records
                mIndex = 2
                mListItems.clear()
                mListItems.addAll(records)
                showListData()
            }else{
                Log.e(TAG, "result=" + bookQueryPage.msg)
                bookQueryPage.msg.let {
                    withContext(Dispatchers.Main){
                        ToastUtils.showToast(it)
                    }
                }
            }
            //
            withContext(Dispatchers.Main){
                refreshLayout_2.finishRefresh()
            }
        }
    }

    private fun loadMoreListData(){
        //
        GlobalScope.launch(Dispatchers.IO){
            val asc = Repo.bookSequence.get(mCurrentMediaListItem!!.idOfBooks())
            val bookQueryPage = MediaModel().bookQueryPage(mCurrentMediaListItem!!.idOfBooks(), mIndex, mPageSize, asc)
            if (bookQueryPage.success) {
                val items: QueryPageBean<BookItemBean> = bookQueryPage.data!!
                val records = items.records
                mIndex++
                mListItems.addAll(records)
                showListData()
            }else{
                Log.e(TAG, "result=" + bookQueryPage.msg)
                bookQueryPage.msg.let {
                    withContext(Dispatchers.Main){
                        ToastUtils.showToast(it)
                    }
                }
            }
            //
            withContext(Dispatchers.Main){
                refreshLayout_2.finishLoadMore()
            }
        }
    }

    private fun showListData(){
        //
        val data = arrayListOf<MediaListItemBean>()
        mListItems.forEach {
            data.add(MediaListItemBean(data = it))
        }
        //
        GlobalScope.launch(Dispatchers.Main){
            mMediaListAdapter.list = data
            mMediaListAdapter.notifyDataSetChanged()
        }
        //
        checkCanLoadMore()
    }

    private fun checkCanLoadMore(){
        if(mListItems.size >= (mCurrentMediaListItem?.chapterTotal ?: 0)){
            refreshLayout_2.setEnableLoadMore(false)
        }else{
            refreshLayout_2.setEnableLoadMore(true)
        }
    }

    override fun onBackPressed() {
        if (isShowRightContent) {
            dismissContentList()
        }else{
            super.onBackPressed()
        }
    }
}*/
